package com.coszero.common.utils.glide;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.coszero.utils.file.FileControl;
import com.coszero.utils.file.FileDirPathUtils;
import com.coszero.utils.utils.TimeUtils;

import java.io.File;
import java.util.concurrent.ExecutionException;


/**
 * Desc： 使用Glide来下载图片
 * 这里的所有Glide操作都不会直接显示在ImageView控件中
 *
 * @author xmqian
 * Email:xmqian93@163.com
 * Date: 2020/8/12 0012 20:40
 */
public class ImageDownUtils {
    //注册图所在的目录
    private static final String ROOT_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "studentImags";
    public static final String REGISTER_DIR = ROOT_DIR + File.separator + "register";
    private static ImageDownUtils imageDownUtils;

    public static ImageDownUtils getInstance() {
        if (imageDownUtils == null) {
            synchronized (ImageDownUtils.class) {
                imageDownUtils = new ImageDownUtils();
                return imageDownUtils;
            }
        }
        return imageDownUtils;
    }

    public void downImageSynch(Context context, String url, DownImageListener listener) {
        downImageSynch(context, url, REGISTER_DIR, TimeUtils.getFileName() + ".jpg", listener);
    }

    /**
     * 同步下载 子线程执行
     *
     * @param context c
     * @param url u
     * @param path 目录路径
     * @param fileName 文件名称
     * @param listener 下载完成监听
     * @apiNote 需要读写权限
     */
    public void downImageSynch(final Context context, final String url, final String path, final String fileName, final DownImageListener listener) {
        try {
            File file = Glide.with(context)
                    .asFile()
                    .load(url)
                    .submit()
                    .get();
//                    LogX.i("###", "原始文件路径:" + file.getAbsolutePath());
            File targe = new File(path);
            if (FileDirPathUtils.makeDir(targe)) {
                File imageFile = new File(targe, fileName);
                FileControl.copy(file, imageFile);
                Log.i("### downImage", "path-->" + file.getPath() + "\n copy to path-->" + targe.getPath());
                listener.success(imageFile);
            }else {
                listener.fail();
            }
//                    if (!targe.exists()) {
//                        boolean mk = targe.mkdirs();
//                        LogX.i("是否创建成功：" + mk);
//                    }
        } catch (InterruptedException e) {
            e.printStackTrace();
            listener.fail();
        } catch (ExecutionException e) {
            e.printStackTrace();
            listener.fail();
        }
    }

    /**
     * 异步下载需要到主线程执行
     *
     * @param context
     * @param url
     */
    @Deprecated
    @SuppressWarnings({"unchecked", "deprecation"})
    public <RT> void downImageAsynch(Context context, String url, @NonNull Class<RT> resourceClass, final DownImageAsynchListener<RT> listener) {
        Glide.with(context).as(resourceClass).load(url).into(new SimpleTarget<RT>() {
            @Override
            public void onResourceReady(@NonNull RT resource, @Nullable Transition<? super RT> transition) {
                listener.success(resource);
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                listener.fail();
            }
        });
    }

    /**
     * 图片预加载，提前缓存图片资源
     *
     * @param context
     * @param url
     */
    public void downImagePreload(Context context, String url) {
        Glide.with(context).load(url).preload();
    }

/**
 * 同步下载回调
 */
public interface DownImageListener {
    void success(File file);

    void fail();
}

public interface DownImageAsynchListener<T> {
    void success(T resource);

    void fail();
}
}
